package com.practice.algorithm.consistentHash;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class HashUtils {
    public static long hashcode(String key) {
        try {
            // 获取 SHA-256 消息摘要实例
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hashBytes = digest.digest(key.getBytes(StandardCharsets.UTF_8));

            // 取前 8 字节转换为 long 类型
            long hash = 0;
            for (int i = 0; i < 8; i++) {
                hash = (hash << 8) | ((long) hashBytes[i] & 0xFF);
            }
            // 确保结果为正数
            return hash & 0x7FFFFFFFFFFFFFFFL;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
}
